package com.siyuanren.gcocp.web.wx;

import cn.hutool.core.io.FileUtil;
import com.siyuanren.gcocp.common.config.PublicConfig;
import com.siyuanren.gcocp.common.util.UUIDUitl;
import com.siyuanren.gcocp.common.web.bean.Result;
import com.siyuanren.gcocp.consts.GcocpConsts;
import com.siyuanren.gcocp.exception.GcocpException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

/**
 */
@Slf4j
@Controller
@RequestMapping("wx/file")
public class WxFileController extends BaseWxController {


    @Autowired
    private WxMpService wxMpService;

    //上传文件会自动绑定到MultipartFile中
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public Result upload(HttpServletRequest request, String data) throws Exception {
        Result result = new Result();
        Base64 base64 = new Base64();
        //注意点：实际的图片数据是从 data:image/jpeg;base64, 后开始的
        String substring = data.substring("data:image/jpeg;base64,".length()-1);
        byte[] k = base64.decode(substring);
        InputStream is = new ByteArrayInputStream(k);
        String fileName = UUIDUitl.getUUID();
        File file = FileUtil.file(PublicConfig.USER_DATA_PATH + File.separator + fileName + GcocpConsts.QRCODE_SUFFIX);
//      String imgFilePath = serverPath + "\\static\\usertemp\\" + fileName + ".jpg";
        //以下其实可以忽略，将图片压缩处理了一下，可以小一点
        double ratio = 1.0;
        BufferedImage image = ImageIO.read(is);
        int newWidth = (int) (image.getWidth() * ratio);
        int newHeight = (int) (image.getHeight() * ratio);
        Image newimage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(newimage, 0, 0, null);
        g.dispose();
        // 不将图片写入磁盘
        ImageIO.write(tag, "jpg", file);
        // 保存推广二维码，并推送给公众号
        result.setData(fileName);

        //先上传
        WxMediaUploadResult wxMediaUploadResult = wxMpService.getMaterialService().mediaUpload(WxConsts.KefuMsgType.IMAGE, file);
        String mediaId = wxMediaUploadResult.getMediaId();
        WxMpKefuMessage reply = new WxMpKefuMessage();
        reply.setToUser(getWxUser().getOpenid());
        reply.setMsgType(WxConsts.KefuMsgType.IMAGE);
        reply.setMediaId(mediaId);
        //再发送
        wxMpService.getKefuService().sendKefuMessage(reply);

        return result;
    }

    /**
     * 文件格式校验
     */
    public void validateUploadFile(MultipartFile file, String extension) {
        if (file == null) {
            // 没有上传文件
            log.info("validateUploadFile file is null");
            throw GcocpException.UPLOAD_FILE_RANGE_ERROR.print();
        }
        if (file.getSize() > GcocpConsts.UPLOAD_IMG_MAX_FILE_SIZE) {
            // 上传的文件文件不能大于10M
            log.info("validateUploadFile file size error");
            throw GcocpException.UPLOAD_FILE_RANGE_ERROR.print();
        }
        if (!"jpg".equals(extension) && !"gif".equals(extension) && !"jpeg".equals(extension) && !"png".equals(extension)) {
            log.info("validateUploadFile extension error");
            throw GcocpException.UPLOAD_FILE_RANGE_ERROR.print();
        }
    }
}
